package com.tgy.leetcode;

public class _59_螺旋矩阵_II {

    public int[][] generateMatrix(int n) {

        int[][] res = new int[n][n];

        int index = 1;

        int left = 0,right = n - 1,top = 0, bottom = n - 1;

        while (left <= right && top <= bottom) {

            for (int i = left; i <= right ; i++) {

                res[top][i] = index++;
            }

            top++;

            if (top > bottom) {

                break;
            }

            for (int i = top; i <= bottom ; i++) {

                res[i][right] = index++;
            }

            right--;

            if (left > right) {
                break;
            }

            for (int i = right; i >= left ; i--) {

                res[bottom][i] = index++;
            }

            bottom--;

            for (int i = bottom; i >= top ; i--) {

                res[i][left] = index++;
            }
            left++;
        }

        return res;
    }

}
